package com.hyh.admin.config.security;




import com.hyh.ad.common.exceptions.AccessDeniedHandlerImpl;
import com.hyh.ad.common.exceptions.AuthenticationEntryPointImpl;
import com.hyh.admin.filter.TokenAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级别的权限认证
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private TokenAuthenticationFilter authenticationFilter;

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/test/hello").permitAll()
                .antMatchers("/api/sysUser/sendCode").permitAll()
                .antMatchers("/api/sysUser/generate").permitAll()
                .antMatchers("/api/sysUser/register").permitAll()
                .antMatchers("/api/mail/send").permitAll()
                .antMatchers("/api/generator/**").permitAll()
                .antMatchers("/api/sysUser/login").permitAll()
                .antMatchers("/api/sysUser/loginByPwd").permitAll()
                //.antMatchers("/api/sysUser/selectUserByUserName").permitAll()
                .antMatchers("/api/sysUser/list").permitAll()
                .antMatchers("/api/sysUser/info").permitAll()
                .antMatchers("/api/sysMenu/**").permitAll()
                .antMatchers("/api/sysRole/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/*").permitAll()
                .antMatchers("/csrf").permitAll()
                .antMatchers("/captchaImage","/api/upload/**").permitAll()
                .antMatchers("/").permitAll()
                .antMatchers("/base/**","/singleChat/**").permitAll()
                .antMatchers("/swagger-ui.html","/swagger-resources/**", "/v2/api-docs").permitAll()
                //放行静态资源
                .antMatchers("/uploads/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*")); // 使用allowedOriginPatterns代替allowedOrigins
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的HTTP方法
        configuration.setAllowedHeaders(Arrays.asList("*")); // 允许所有请求头
        configuration.setAllowCredentials(true); // 允许发送凭据
        configuration.setMaxAge(3600L); // 预检请求的有效期，单位秒
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration); // 对所有路径应用上面的CORS配置
        return source;
    }
}
